import cv2
video_path = './vtest.avi'
cap = cv2.VideoCapture(video_path)
# 混合高斯模型
fgbg = cv2.createBackgroundSubtractorMOG2()
thresh = 200

while True:
    ret, frame = cap.read()
    if not ret:
        break

    fgmask = fgbg.apply(frame)

    _, fgmask = cv2.threshold(fgmask, 30, 0xff, cv2.THRESH_BINARY)

    bgImage = fgbg.getBackgroundImage()

    cnts = cv2.findContours(fgmask.copy(), cv2.RETR_EXTERNAL,
                            cv2.CHAIN_APPROX_SIMPLE)

    count = 0

    for c in cnts[1]:
        area = cv2.contourArea(c)
        if (area < thresh):
            continue
        count += 1
        x, y, w, h = cv2.boundingRect(c)
        cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 0xff, 0), 2)

    print('count', count, 'targets', '\n')
    cv2.imshow('frame', frame)
    cv2.imshow('Background', bgImage)
    cv2.imshow('fgmask', fgmask)

    key = cv2.waitKey(30)
    if key == 27:
        break
cap.release()
cv2.destroyAllWindows()
